# -*- coding: utf-8 -*-
import copy
import glob
import os
import sys

import openpyxl


class ExcelRead:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            # 创建新的实例
            instance = super().__new__(cls)
            cls._instance = instance
        return cls._instance

    def __init__(self):
        # 判断实例是否已经初始化
        if not hasattr(self, 'authorization_time'):
            # sheet_1
            # 设备ip
            self.col_device_identifier_pos = -1
            self.col_device_identifier_title = "设备标识"
            # 操作步骤
            self.col_step_pos = -1
            self.col_step_title = "操作步骤"
            # 关键字
            self.col_key_word_pos = -1
            self.col_key_word_title = "关键字"
            # 测试数据
            self.col_test_data_pos = -1
            self.col_test_data_title = "测试数据"

            # sheet_2
            self.device_identifier = None
            self.device_identifier_list = []
            self.row_device_identifier_pos = -1
            self.row_device_identifier_title = "设备标识"
            self.click_interval = None
            self.row_click_interval_pos = -1
            self.row_click_interval_title = "点击间隔ms"

            # testdata/data_files目录
            self.test_case_path = "testdata/data_files"
            self.test_case_file_path = None
            self.get_test_case_file_path()
            self.workbook = openpyxl.load_workbook(self.test_case_file_path)
            self.sheet_names = self.workbook.sheetnames
            self.test_parameter_init()
            self._use_case_elements_pos()
            self.use_case_datas = self._get_use_cases_data()

    # 获取测试数据文件路径
    def get_test_case_file_path(self):
        # 使用 glob 模块查找匹配 app_test*.xlsx 的文件
        all_app_test_files = glob.glob(os.path.join(self.test_case_path, "app_test*.xlsx"))
        print("获取testdata/data_files目录下唯一一个以app_test*.xlsx格式命名的测试文件路径")
        for app_test_file in all_app_test_files:
            print(app_test_file)
        if len(all_app_test_files) == 1:
            self.test_case_file_path = all_app_test_files[0]
            print(f"{self.test_case_file_path}存放数据类型都为文本")
        else:
            print(f"请确保{self.test_case_path}目录下只有一个测试用例文件，文件命名格式：app_test*.xlsx")
            input("即将退出程序")
            sys.exit(0)

    def test_parameter_init(self):
        print("\n*****************************脚本参数**********************************\n")
        sheet = self.workbook.worksheets[1]
        row_titles = [sheet.cell(row=i, column=1).value for i in range(1, sheet.max_row)]
        if self.row_device_identifier_title in row_titles:
            self.row_click_interval_pos = row_titles.index(self.row_device_identifier_title)
            self.device_identifier = sheet.cell(self.row_click_interval_pos + 1, 2).value
            if self.device_identifier is not None and self.device_identifier not in self.device_identifier_list:
                self.device_identifier_list.append(self.device_identifier)
            print("{}: {}".format(self.row_device_identifier_title, self.device_identifier))
        if self.row_click_interval_title in row_titles:
            self.row_click_interval_pos = row_titles.index(self.row_click_interval_title)
            self.click_interval = sheet.cell(self.row_click_interval_pos + 1, 2).value
            print("{}: {}".format(self.row_click_interval_title, self.click_interval))
        print("\n*****************************脚本参数**********************************\n")

    def get_use_case_title(self):
        return self.sheet_names[0]

    def _get_column_titles_from_excel(self):
        sheet = self.workbook.worksheets[0]
        column_titles = [cell.value for cell in sheet[1]]
        return column_titles

    # 定位存在的用例元素位置
    def _use_case_elements_pos(self):
        column_titles = self._get_column_titles_from_excel()
        if self.col_device_identifier_title in column_titles:
            self.col_device_identifier_pos = column_titles.index(self.col_device_identifier_title)
        if self.col_step_title in column_titles:
            self.col_step_pos = column_titles.index(self.col_step_title)
        if self.col_key_word_title in column_titles:
            self.col_key_word_pos = column_titles.index(self.col_key_word_title)
        if self.col_test_data_title in column_titles:
            self.col_test_data_pos = column_titles.index(self.col_test_data_title)

    def _get_use_cases_data(self):
        print("\n*****************************测试数据**********************************\n")
        sheet = self.workbook.worksheets[0]
        use_case_data_template = []
        use_case_datas = []
        for row in range(self.col_test_data_pos + 5):
            use_case_data_template.append("")
        for row in range(2, sheet.max_row + 1):
            if self.col_key_word_pos != -1:
                key_word_text = sheet.cell(row, self.col_key_word_pos + 1).value
                if key_word_text is not None:
                    use_case_data = copy.deepcopy(use_case_data_template)
                    use_case_data[self.col_key_word_pos] = key_word_text

                    if self.col_device_identifier_pos != -1:
                        device_identifier_text = sheet.cell(row, self.col_device_identifier_pos + 1).value
                        if device_identifier_text is not None:
                            use_case_data[self.col_device_identifier_pos] = device_identifier_text
                            if device_identifier_text not in self.device_identifier_list:
                                self.device_identifier_list.append(device_identifier_text)
                    if self.col_step_pos != -1:
                        step_text = sheet.cell(row, self.col_step_pos + 1).value
                        if step_text is not None:
                            use_case_data[self.col_step_pos] = step_text
                    if self.col_test_data_pos != -1:
                        for i in range(5):
                            data_text = sheet.cell(row, self.col_test_data_pos + i + 1).value
                            if data_text is not None:
                                use_case_data[self.col_test_data_pos + i] = data_text
                    use_case_datas.append(use_case_data)
                    print("测试步骤：{}".format(use_case_data))
        print("\n*****************************测试数据**********************************\n")
        return use_case_datas





